#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-09-11 21:26:07
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import conf
import db
import re
import hashlib
import MySQLdb


class User(object):
    # 初始化类

    def __init__(self, phone=None, passwd=None, reg_info=None):
        self.conn, self.cur = db.db_object()
        self.phone = phone
        self.passwd = passwd
        self.reg_info = reg_info

    # 查询用户是否存在
    def user_exist(self):
        query = 'SELECT phone FROM user WHERE phone="{phone}"'.format(
            phone=self.phone)
        if db.db_select_on(query):
            return True  # 用户已存在
        else:
            return False  # 用户不存在

    # 查看用户状态
    def user_status(self):
        query = 'SELECT status FROM user WHERE phone="{phone}"'.format(
            phone=self.phone)
        status = db.db_select_on(query)[0]  # 获取第一个字段
        if status == 1:
            return True  # 用户激活
        else:
            return False  # 用户未激活

    # 判断手机号格式的正确性
    def check_phone(self):
        par = r'^1[3|4|5|7|8]\d{9}$'
        if re.match(par, self.phone):
            return True
        else:
            return False

    # 登录密码验证
    def check_pass(self):
        query = 'SELECT passwd FROM user WHERE phone="{phone}"'.format(
            phone=self.phone)
        dbpasswd = db.db_select_on(query)[0]  # 获取第一个字段
        db.db_close()  # 关闭数据库信息
        if dbpasswd == db.md5(self.passwd):  # 密码通过MD5加密
            return True
        else:
            return False

    # 判断信息完整度
    def check_reg_info(self):
        # 判断子集
        se = self.reg_info.keys()
        if 'phone' in se and 'nickName' is se and 'passwd' in se and 'class_type' in se and 'class_num' in se and 'en_passwd' in se:
            return True  # 信息完整
        else:
            return False

    # 判断注册密码是否一致
    def check_enpasswd(self):
        if self.reg_info['passwd'] == self.reg_info['en_passwd']:
            return True
        else:
            return False

    # 判断注册密码长度是否为6-20位
    def check_pass_len(self):
        if 6 <= len(self.reg_info['passwd']) <= 20:
            return True
        else:
            return False

    # 用户登录
    def login(self):
        if not self.user_exist():
            result = {
                'code': 1001,
                'message': conf._code.get(1001, '用户不存在')
            }
            return result
        elif not self.user_status():
            result = {
                'code': 1002,
                'message': conf._code.get(1002, '用户未激活')
            }
            return result
        elif not self.check_pass():
            result = {
                'code': 1003,
                'message': conf._code.get(1003, '密码错误')
            }
            return result
        else:
            result = {
                'code': 0000,
                'message': conf._code.get(0000, '成功')
            }
            return result

    # 用户注册
    def register(self):
        self.phone = self.reg_info['phone']
        if self.user_exist():
            result = {
                'code': 1014,
                'message': conf._code.get(1014, '手机号已注册，请更换手机号')
            }
            return result
        elif not self.check_reg_info():
            result = {
                'code': 1010,
                'message': conf._code.get(1010, '请填写相应信息')
            }
            return result
        elif not self.check_phone():
            result = {
                'code': 1011,
                'message': conf._code.get(1011, '手机号格式不正确')
            }
            return result
        elif not self.check_pass_len():
            result = {
                'code': 1017,
                'message': conf._code.get(1017, '密码长度为6-20位')
            }
            return result
        elif not self.check_enpasswd():
            result = {
                'code': 1012,
                'message': conf._code.get(1012, '密码不一致')
            }
            return result
        else:
            passwd = db.md5(self.reg_info['passwd'])
            query = '''
                INSERT INTO user (phone,nickName,passwd,class_type,class_num)
                    VALUES(
                        '{phone}','{nickName}','{passwd}','{class_type}', '{class_num}'
                            )
                '''.format(phone=self.reg_info['phone'], nickName=self.reg_info['nickName'], passwd=passwd,
                           class_type=self.reg_info['class_type'],
                           class_num=self.reg_info['class_num'])
            try:
                db.db_insert_on(query)
                db.db_close()
                result = {
                    'code': 0000,
                    'message': '注册成功'
                }
                return result
            except Exception, e:
                result = {
                    'code': 1013,
                    'message': '注册失败'
                }
                return result

    # 用户状态查询
    def user_info(self):
        query = 'SELECT id,phone,nickName,class_type,class_num,status FROM user;'
        try:
            data = db.db_select_all(query)
            db.db_close()
            result = {
                'code': 0000,
                'message': conf._code.get(0000, '成功'),
                'result': {
                    'data': data
                }
            }
            return result
        except Exception, e:
            result = {
                'code': 1015,
                'message': str(e)
            }

    # 用户激活
    def status_on(self, phone):
        self.phone = phone
        query = 'UPDATE user SET status=1 WHERE phone="{phone}"'.format(
            phone=self.phone)
        try:
            if not self.check_phone():
                result = {
                    'code': 1011,
                    'message': conf._code.get(1011, '手机号格式不正确')
                }
                return result
            elif not self.user_exist():
                result = {
                    'code': 1001,
                    'message': conf._code.get(1001, '用户不存在')
                }
                return result
            else:
                db.db_insert_on(query)
                db.db_close()
                result = {
                    'code': 0000,
                    'message': conf._code.get(0000, '成功')
                }
                return result
        except Exception, e:
            result = {
                'code': 1016,
                'message': str(e)
            }
            return result

    # 用户信息查询
    def info(self, phone):
        query = 'SELECT id,phone,nickName,class_type,class_num,sex,qq FROM user WHERE phone="{phone}";'.format(
            phone=phone)
        try:
            data = db.db_select_all(query)
            db.db_close()
            result = {
                'code': 0000,
                'message': conf._code.get(0000, '成功'),
                'result': {
                    'data': data
                }
            }
            return result
        except Exception, e:
            result = {
                'code': 1015,
                'message': str(e)
            }
            return result

    # 用户信息修改

    def user_edit(self, user_info=None):
        query = '''
            UPDATE user SET
                nickName="{nickName}",class_type="{class_type}",class_num="{class_num}",
                sex="{sex}",qq="{qq}" WHERE phone="{phone}"
            '''.format(nickName=user_info.get('nickName'),class_type=user_info.get('class_type'),class_num=user_info.get('class_num'),\
                sex=user_info.get('sex'),qq=user_info.get('qq'),phone=user_info.get('phone'))
        print query
        try:
            data = db.db_update_on(query)
            print 'data: ',data
            db.db_close()
            if data == 1 or data == 0:
                result = {
                    'code': 0000,
                    'message': conf._code.get(0000, '成功')
                }
            else:
                result = {
                    'code': 1018,
                    'message': conf._code.get(1018, '用户信息修改失败')
                }
            return result
        except Exception, e:
            result = {
                'code': 1018,
                'message': str(e)
            }
            return result


if __name__ == '__main__':
    # #登录
    # u = User(phone='13100000001',passwd='111111')
    # result = u.login()
    # print result
    # print result['message']

    # 注册
    # reg_info = {
    #     'phone':'13100000003',
    #     'passwd':'111111',
    #     'class_type':'python',
    #     'class_num':'3',
    #     'en_passwd':'111111'
    # }
    # u = User(reg_info=reg_info)
    # result = u.register()
    # print result
    # print result['message']

    # 用户查看所有信息测试
    # u = User()
    # print u.user_info()

    # #用户激活测试
    u = User(phone='13100000002')
    result = u.status_on()
    print result
    print result['message']
